<template>
  <el-container>
    <jcx-search v-model:show-search="showSearch" :show-button="false" :query-form="queryParams"
                :power="'system:tenant:lists'" @handle-reset-query="handleResetQuery" @handle-search="handleSearch">
      <el-col :span="12">
        <el-form-item label="租户名称" prop="name">
          <el-input placeholder="租户名称" clearable v-model="queryParams.name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="启用状态" prop="enabled">
          <el-select placeholder="启用状态" clearable v-model="queryParams.enabled">
            <el-option key="1" label="启用" :value="true"></el-option>
            <el-option key="0" label="停用" :value="false"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </jcx-search>
    <el-header>
      <div class="left-panel">
        <div class="left-panel-search" v-if="showSearch">
          <el-button type="primary" plain icon="el-icon-search" @click="handleSearch"
                     v-power="'system:tenant:lists'"></el-button>
          <el-button type="info" plain icon="el-icon-refresh" @click="handleResetQuery"></el-button>
        </div>
      </div>
      <div class="right-panel">
        <jcx-table-bar :column-list="columnList" v-model:config="config" v-model:show-search="showSearch"
                       @query-table="getList"></jcx-table-bar>
      </div>
    </el-header>
    <el-main class="no-padding">
      <el-table style="width: 100%" ref="table" row-key="id" v-loading="loading" :data="dataList"
                :stripe="config.stripe" :border="config.border" :size="config.size"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <template v-for="(column, index) in columnList" :key="index">
          <el-table-column v-if="!column.hide" :label="column.label" :prop="column.prop" :align="column.align"
                           :width="column.width" :fixed="column.fixed">
            <template #default="scope">
              <jcx-render-column v-if="column.render" :scope="scope" :render="column.render"></jcx-render-column>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </el-main>
    <el-footer>
      <div class="jcx-table-page">
        <div class="jcx-table-do">
          <el-button type="primary" plain icon="el-icon-plus" @click="handleAddClick"
                     v-powers="['system:user:lists' , 'system:source:lists']"></el-button>
          <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple"
                     @click="handleDeleteClick" v-power="'system:tenant:del'"></el-button>
          <el-button type="warning" plain icon="el-icon-edit" :disabled="single" @click="handleEditClick"
                     v-powers="['system:tenant:info' , 'system:user:lists' , 'system:source:lists']"></el-button>
        </div>
        <div class="jcx-table-pagination">
          <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                         :small="true" :page-sizes="[10, 20, 30, 40, 50]" v-model:currentPage="queryParams.pageNum"
                         v-model:page-size="queryParams.pageSize" @current-change="getList"
                         @update:page-size="getList"></el-pagination>
        </div>
      </div>
    </el-footer>
    <el-dialog destroy-on-close append-to-body :close-on-click-modal="false" width="1080px" :title="title"
               v-model="open" @closed="handleCancel">
      <div v-if="tenantForm.id">
        <!-- 修改 -->
        <tenant-form-vue ref="tenantFormRef" :form="tenantForm"></tenant-form-vue>
      </div>
      <div v-else>
        <el-tabs type="border-card">
          <el-tab-pane label="租户信息">
            <tenant-form-vue ref="tenantFormRef" :form="tenantForm"></tenant-form-vue>
          </el-tab-pane>
          <el-tab-pane label="部门信息">
            <dept-form-vue ref="deptFormRef" :form="deptForm"></dept-form-vue>
          </el-tab-pane>
          <el-tab-pane label="岗位信息">
            <post-form-vue ref="postFormRef" :form="postForm"></post-form-vue>
          </el-tab-pane>
          <el-tab-pane label="角色信息">
            <role-form-vue ref="roleFormRef" :form="roleForm"></role-form-vue>
          </el-tab-pane>
          <el-tab-pane label="用户信息">
            <user-form-vue ref="userFormRef" :form="userForm"></user-form-vue>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <el-button plain :type="tenantForm.id ? 'warning' : 'primary'" :loading="saving" @click="handleSubmitForm"
                   v-power="tenantForm.id ? 'system:tenant:edit' : 'system:tenant:add'">
          {{ tenantForm.id ? '修 改' : '保 存' }}
        </el-button>
        <el-button plain type="info" @click="handleCancel">取 消</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import {onMounted, ref} from "vue";
import tenantFormVue from "./form/tenantForm.vue";
import deptFormVue from "./form/deptForm.vue";
import postFormVue from "./form/postForm.vue";
import roleFormVue from "./form/roleForm.vue";
import userFormVue from "./form/userForm.vue";
import tenantApi from "@/api/system/tenant";
import renderUtil from "@/utils/render";
import modal from "@/utils/modal";
import crypto from "@/utils/crypto";
import storage from "@/utils/storage";

// 是否显示搜索栏
const showSearch = ref(true);
// 查询条件
const queryParams = ref({
  name: null,
  enabled: null,
  pageNum: 1,
  pageSize: 10
});
// 分页总条数
const total = ref(0);
// 表格配置
const config = ref({
  // 表格大小
  size: "default",
  // 表格边框
  border: true,
  // 表格斑马图纹
  stripe: true
});
// 表格数据列表
const dataList = ref([]);
// 表格列数据
const columnList = ref([
  {
    label: '租户标识',
    prop: 'code',
    hide: false,
    align: 'center'
  },
  {
    label: '租户名称',
    prop: 'name',
    hide: false,
    align: 'center'
  },
  {
    label: '数据源标识',
    prop: 'sourceCode',
    hide: false,
    align: 'center'
  },
  {
    label: '租户负责人',
    prop: 'userName',
    hide: false,
    align: 'center'
  },
  {
    label: '租户联系方式',
    prop: 'phone',
    hide: false,
    align: 'center'
  },
  {
    label: '租户联系邮箱',
    prop: 'email',
    hide: false,
    align: 'center'
  },
  {
    label: '授权开始日期',
    prop: 'startDate',
    hide: false,
    align: 'center'
  },
  {
    label: '授权结束日期',
    prop: 'endDate',
    hide: false,
    align: 'center'
  },
  {
    label: '是否启用',
    prop: 'enabled',
    hide: false,
    align: 'center',
    render: (h, row) => {
      return renderUtil.renderYesOrNo(row.enabled, '启用', '停用');
    }
  },
  {
    label: '排序',
    prop: 'sort',
    hide: false,
    align: 'center'
  },
  {
    label: '创建时间',
    prop: 'createTime',
    hide: false,
    align: 'center'
  },
  {
    label: '备注',
    prop: 'remark',
    hide: false,
    align: 'center',
  },
  {
    label: '操作',
    prop: 'operation',
    hide: false,
    align: 'center',
    width: 200,
    render: (h, row) => {
      return renderUtil.renderButtonArray(row, [
        {
          type: 'danger',
          icon: 'el-icon-delete',
          size: 'small',
          powerCodeList: 'system:tenant:del',
          clickFunction: handleDeleteClick,
        },
        {
          type: 'warning',
          icon: 'el-icon-edit',
          size: 'small',
          powerCodeList: ['system:tenant:info', 'system:user:lists', 'system:source:lists'],
          clickFunction: handleEditClick,
        }
      ])
    },
  },
]);
// 表格中被选中的数据列表
const selectList = ref([]);
// 加载动画
const loading = ref(false);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 表单组件
const tenantFormRef = ref(null);
const deptFormRef = ref(null);
const postFormRef = ref(null);
const roleFormRef = ref(null);
const userFormRef = ref(null);
// 保存状态
const saving = ref(false);
// 弹出层状态
const open = ref(false);
// 弹出层标题
const title = ref('新增租户');
// 表单数据
const tenantForm = ref({
  id: null,
  code: null,
  name: null,
  userId: null,
  phone: null,
  email: null,
  logo: null,
  startDate: null,
  endDate: null,
  sourceId: null,
  sort: null,
  remark: null,
  enabled: null
});
const deptForm = ref({
  id: null,
  code: 'SYS_SUPER_DEPT',
  name: null,
  parentId: 0,
  userId: 'SYS_SUPER_USER',
  phone: null,
  email: null,
  sort: 1,
  remark: null,
  enabled: true
});
const postForm = ref({
  id: null,
  code: 'SYS_SUPER_POST',
  name: null,
  scope: 'ALL',
  sort: 1,
  remark: null,
  enabled: true,
  deptIdList: null
});
const roleForm = ref({
  id: null,
  code: 'SYS_SUPER_ROLE',
  name: null,
  sort: 1,
  remark: null,
  enabled: true,
  menuIdList: null
});
const userForm = ref({
  id: null,
  code: 'SYS_SUPER_USER',
  name: null,
  deptId: 'SYS_SUPER_DEPT',
  username: null,
  password: null,
  phone: null,
  email: null,
  sex: null,
  avatar: null,
  sort: 1,
  remark: null,
  enabled: true,
  postIdList: ['SYS_SUPER_POST'],
  roleIdList: ['SYS_SUPER_ROLE'],
});

// 查询按钮触发方法
const handleSearch = () => {
  getList();
}

// 重置查询条件触发按钮
const handleResetQuery = () => {
  queryParams.value = {
    name: null,
    enabled: null,
    pageNum: 1,
    pageSize: 10
  };
  handleSearch();
}

// 获取数据方法
const getList = () => {
  loading.value = true;
  tenantApi.lists.get(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  })
}

// 表格选中触发方法
const handleSelectionChange = (selection) => {
  selectList.value = selection.map(item => item);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增按钮方法
const handleAddClick = () => {
  title.value = '新增租户';
  open.value = true;
}

// 删除按钮方法
const handleDeleteClick = (row) => {
  const idList = row.id ? [row.id] : selectList.value.map(item => item.id);
  modal.confirm(`确定删除选中的 ${idList.length} 项吗？`).then(() => {
    tenantApi.del.delete(idList).then(response => {
      if (response.status) {
        modal.successMessage(response.message);
        getList();
      } else {
        modal.errorMessage(response.message);
      }
    });
  }).catch(() => {
    modal.infoMessage("用户取消操作");
  })
}

// 编辑按钮方法
const handleEditClick = (row) => {
  const id = row.id || selectList.value[0].id;
  tenantApi.info.get(id, true).then(response => {
    tenantForm.value = response.data;
    title.value = '编辑租户';
    open.value = true;
  });
}

// 重置 form
const resetForm = (formEl) => {
  tenantForm.value = {
    id: null,
    code: null,
    name: null,
    userId: null,
    phone: null,
    email: null,
    logo: null,
    startDate: null,
    endDate: null,
    sourceId: null,
    sort: null,
    remark: null,
    enabled: null
  };
  if (!formEl) return;
  formEl.resetFields();
}

// 关闭弹窗
const handleCancel = () => {
  if (tenantForm.value.id) {
    // 修改
    resetForm(tenantFormRef.value.getFormRef());
  } else {
    // 新增
    resetForm(tenantFormRef.value.getFormRef());
    resetForm(deptFormRef.value.getFormRef());
    resetForm(postFormRef.value.getFormRef());
    resetForm(roleFormRef.value.getFormRef());
    resetForm(userFormRef.value.getFormRef());
  }
  open.value = false;
}

// 弹窗提交
const handleSubmitForm = async () => {
  let flag = true;
  await tenantFormRef.value.getFormRef().validate(valid => {
    if (!valid) {
      flag = false;
      modal.errorMessage("租户信息校验失败");
    }
  })
  if (!flag) return;
  if (!tenantForm.value.id) {
    // 新增校验表单
    await deptFormRef.value.getFormRef().validate(valid => {
      if (!valid) {
        flag = false;
        modal.errorMessage("部门信息校验失败");
      }
    })
    if (!flag) return;
    await postFormRef.value.getFormRef().validate(valid => {
      if (!valid) {
        flag = false;
        modal.errorMessage("岗位信息校验失败");
      }
    })
    if (!flag) return;
    await roleFormRef.value.getFormRef().validate(valid => {
      if (!valid) {
        flag = false;
        modal.errorMessage("角色信息校验失败");
      }
    })
    if (!flag) return;
    await userFormRef.value.getFormRef().validate(valid => {
      if (!valid) {
        flag = false;
        modal.errorMessage("用户信息校验失败");
      }
    })
    if (!flag) return;
  }
  saving.value = true;
  // 修改
  if (tenantForm.value.id) {
    tenantApi.edit.put(tenantForm.value).then(response => {
      modal.message(response.message, {type: response.status ? 'success' : 'error'})
      saving.value = false;
      if (response.status) {
        handleCancel();
        handleSearch();
      }
    })
  }
  // 新增
  else {
    tenantForm.value.addSysDept = deptForm.value;
    tenantForm.value.addSysPost = postForm.value;
    tenantForm.value.addSysRole = roleForm.value;
    tenantForm.value.addSysUser = userForm.value;
    userForm.value.password = crypto.RSA.encrypt(userForm.value.password);
    tenantApi.add.post(tenantForm.value).then(response => {
      modal.message(response.message, {type: response.status ? 'success' : 'error'})
      saving.value = false;
      if (response.status) {
        handleCancel();
        handleSearch();
      }
    })
  }
}

// 页面加载时触发方法
onMounted(() => {
  getList();
})
</script>

<style scoped lang="scss">
</style>
